package com.yinhai.uid.config;

import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.Set;

/**
 * @author taojie
 * @date 2018/12/26.
 */
public class UidRedisClusterConfiguration extends RedisClusterConfiguration {

    public void setClusterNodes(Set<String> hostAndPorts) {
        Iterator iterator = hostAndPorts.iterator();
        while(iterator.hasNext()) {
            String hostAndPort = (String) iterator.next();
            this.addClusterNode(this.buildNodeFromString(hostAndPort));
        }
    }

    private RedisNode buildNodeFromString(String hostAndPort) {
        String[] args = StringUtils.split(hostAndPort, ":");
        Assert.notNull(args, "HostAndPort need to be seperated by  ':'.");
        Assert.isTrue(args.length == 2, "Host and Port String needs to specified as host:port");
        return new RedisNode(args[0], Integer.valueOf(args[1]));
    }
}
